package com.smasher.backup.dialog.select.model

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

class TargetPagingViewModel<T : Any>(private val backend: TargetBackendService) : ViewModel() {

    private val _searchQuery = MutableStateFlow("")

    private val _pagingData = MutableStateFlow<PagingData<T>>(PagingData.empty())
    val pagingData: StateFlow<PagingData<T>> = _pagingData

    init {
        viewModelScope.launch {
            _searchQuery
                .collectLatest { query ->
                    createPager(query).flow
                        .cachedIn(viewModelScope)
                        .collect { pagingData ->
                            _pagingData.value = pagingData
                        }
                }
        }
    }

//    val pagingData: StateFlow<PagingData<T>> =
//        _searchQuery.debounce(300) // 添加防抖
//            .flatMapLatest { query ->
//                createPager(query).flow
//                    .cachedIn(viewModelScope)
//            }.stateIn(
//                scope = viewModelScope,
//                started = SharingStarted.WhileSubscribed(5_000),
//                initialValue = PagingData.empty()
//            )

    // 改进点3：动态构建 Pager
    private fun createPager(query: String): Pager<Int, T> {
        return Pager(
            config = PagingConfig(
                pageSize = 10,
                enablePlaceholders = false,
                initialLoadSize = 30,
                prefetchDistance = 3
            ),
            pagingSourceFactory = { TargetPagingSource(backend, query) }
        )
    }

    // 改进点4：搜索方法优化
    fun search(query: String) {
        viewModelScope.launch {
            Log.e(TAG, "search: ", )
            _searchQuery.emit(query)
        }
    }

    // 改进点5：刷新机制优化
    fun refresh() {
        _searchQuery.update { it } // 通过相同值触发刷新
    }

    companion object {
        const val TAG = "TargetPaging"
    }

}